package com.webchat.aigc.llm;


import com.webchat.common.bean.APIResponseBean;
import com.webchat.common.bean.APIResponseBeanUtil;
import com.webchat.common.enums.HttpRequstMethodEnum;
import com.webchat.common.helper.SseEmitterHelper;
import com.webchat.common.util.HttpClientUtil;
import com.webchat.common.util.JsonUtil;
import com.webchat.common.util.UrlUtil;
import com.webchat.domain.dto.bot.BotPluginDTO;
import com.webchat.domain.dto.bot.LLMParameterDTO;
import com.webchat.domain.dto.bot.PluginParameterDTO;
import com.webchat.domain.vo.llm.image.ImageGenerateResponse;
import com.webchat.domain.vo.llm.image.RequestGenerateBaseParam;
import com.webchat.domain.vo.llm.image.RequestGenerateParam;
import com.webchat.domain.vo.request.mess.ChatMessageRequestVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Service
public class AiBotPluginService {


    @Autowired
    private AiParameterService aiParameterService;
    @Autowired
    private GPTChatService gptChatService;

    @Value("${webchat.api.access-key}")
    private String accessKey;
    @Value("${webchat.api.secret-key}")
    private String secretKey;

    private static final String LLM_QUESTION_TEMPLATE = "用户问题：%s \n 业务数据：%s \n, 要求：回复简介明了，不要啰里八嗦！";

    public String doChat(ChatMessageRequestVO chatMessage, String bizCode, String function) {

        String message = chatMessage.getMessage();
        String senderId = chatMessage.getSenderId();

        LLMParameterDTO parameterDTO;
        try {
            /**
             * 插件类意图处理: 抽参 + 参数trans
             */
            parameterDTO = aiParameterService.getParameter(senderId, message, function);
            log.info("【大模型插件意图参数抽取】====> message:{}, function:{}, parameterDTO:{}",
                    message, function, JsonUtil.toJsonString(parameterDTO));
            SseEmitterHelper.send(bizCode, senderId, JsonUtil.toJsonString(parameterDTO));
        } catch (Exception e) {
            SseEmitterHelper.send(bizCode, senderId, "插件参数抽取异常，请优化输入！");
            return null;
        }

        SseEmitter sseEmitter = SseEmitterHelper.get(bizCode, senderId);

        /**
         * 插件调用
         */
        BotPluginDTO plugin = parameterDTO.getPlugin();
        String api = plugin.getApi();
        String method = plugin.getMethod();
        // header鉴权参数
        Map<String, String> headers = this.requestHeaders();
        // 请求参数
        Map<String, Object> requestParameter =
                parameterDTO.getParameters().stream().collect(
                        Collectors.toMap(PluginParameterDTO::getName, PluginParameterDTO::getValue));
        // 插件响应结果
        APIResponseBean apiResponseBean = null;
        try {
            if (HttpRequstMethodEnum.GET.name().equals(method.toUpperCase())) {
                String requestUrl = UrlUtil.buildUrl(api, requestParameter);
                ResponseEntity<APIResponseBean> response = (ResponseEntity<APIResponseBean>)
                        HttpClientUtil.getObjectFromUrl(requestUrl, headers, APIResponseBean.class);
                apiResponseBean = response.getBody();
            } else if (HttpRequstMethodEnum.POST.name().equals(method.toUpperCase())) {
                apiResponseBean = HttpClientUtil.postObjectForUrl(api, headers, requestParameter, APIResponseBean.class);
            }
            if (!APIResponseBeanUtil.isOk(apiResponseBean)) {
                SseEmitterHelper.send(bizCode, senderId, "插件服务调用异常，异常响应：" + JsonUtil.toJsonString(apiResponseBean));
                return null;
            }
            // 插件返回业务数据
            Object bizData = apiResponseBean.getData();
            // 插件返回业务数据，LLM实现问答增强
            String botInputMessage = String.format(LLM_QUESTION_TEMPLATE, message, JsonUtil.toJsonString(bizData));
            chatMessage.setMessage(botInputMessage);
            // 模型基于插件返回结果实现增强效果
            return gptChatService.chat(sseEmitter, chatMessage);
        } catch (Exception e) {
            SseEmitterHelper.send(bizCode, senderId, "工具链调用异常！" + e.getMessage());
        }
        return null;
    }

    private Map<String, String> requestHeaders() {
        Map<String, String> headers = new HashMap<>();
        headers.put("access-key", accessKey);
        headers.put("secret-key", secretKey);
        return headers;
    }
}
